// 认证和用户管理工具

import { ROLES } from './permission.js'

// 默认用户信息
const DEFAULT_USER = {
  id: 1,
  name: '张经理',
  role: ROLES.PURCHASER,
  department: '采购部',
  avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=80&h=80&fit=crop&crop=face'
}

// 初始化用户信息
export const initUser = () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (!userInfo) {
      // 如果没有用户信息，设置默认用户
      uni.setStorageSync('userInfo', DEFAULT_USER)
      return DEFAULT_USER
    }
    return userInfo
  } catch (error) {
    console.error('初始化用户信息失败:', error)
    return DEFAULT_USER
  }
}

// 获取当前用户信息
export const getCurrentUser = () => {
  try {
    return uni.getStorageSync('userInfo') || DEFAULT_USER
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return DEFAULT_USER
  }
}

// 更新用户信息
export const updateUser = (userData) => {
  try {
    const currentUser = getCurrentUser()
    const updatedUser = { ...currentUser, ...userData }
    uni.setStorageSync('userInfo', updatedUser)
    return updatedUser
  } catch (error) {
    console.error('更新用户信息失败:', error)
    return null
  }
}

// 切换用户角色
export const switchUserRole = (role) => {
  if (!Object.values(ROLES).includes(role)) {
    console.error('无效的角色:', role)
    return false
  }
  
  const updatedUser = updateUser({ role })
  return updatedUser !== null
}

// 检查用户是否已登录
export const isLoggedIn = () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    return userInfo && userInfo.id
  } catch (error) {
    console.error('检查登录状态失败:', error)
    return false
  }
}

// 登录
export const login = (userData) => {
  try {
    const userInfo = {
      ...DEFAULT_USER,
      ...userData,
      loginTime: new Date().toISOString()
    }
    uni.setStorageSync('userInfo', userInfo)
    return userInfo
  } catch (error) {
    console.error('登录失败:', error)
    return null
  }
}

// 登出
export const logout = () => {
  try {
    uni.removeStorageSync('userInfo')
    return true
  } catch (error) {
    console.error('登出失败:', error)
    return false
  }
}

// 获取用户角色
export const getUserRole = () => {
  const user = getCurrentUser()
  return user.role || ROLES.PURCHASER
}

// 检查用户是否有特定角色
export const hasRole = (role) => {
  const userRole = getUserRole()
  return userRole === role
}

// 检查用户是否有任一角色
export const hasAnyRole = (roles) => {
  const userRole = getUserRole()
  return roles.includes(userRole)
}

// 获取用户显示信息
export const getUserDisplayInfo = () => {
  const user = getCurrentUser()
  return {
    name: user.name,
    role: user.role,
    department: user.department,
    avatar: user.avatar
  }
}

// 模拟登录API
export const mockLogin = (username, password) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟不同的用户角色
      const users = {
        'purchaser': { role: ROLES.PURCHASER, name: '张采购', department: '采购部' },
        'business': { role: ROLES.BUSINESS, name: '李业务', department: '业务部' },
        'logistics': { role: ROLES.LOGISTICS, name: '王物流', department: '物流部' },
        'data': { role: ROLES.DATA_MAINTAINER, name: '赵数据', department: '数据部' },
        'finance': { role: ROLES.FINANCE, name: '钱财务', department: '财务部' },
        'admin': { role: ROLES.ADMIN, name: '孙管理员', department: '管理部' }
      }
      
      const user = users[username]
      if (user && password === '123456') {
        const userInfo = login({
          name: user.name,
          role: user.role,
          department: user.department
        })
        resolve(userInfo)
      } else {
        reject(new Error('用户名或密码错误'))
      }
    }, 1000)
  })
}

// 导出默认用户信息
export { DEFAULT_USER } 